package tuvienna.jade.table;

import tuvienna.jade.Constants;
import tuvienna.jade.InterestSet;
import jade.core.AID;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.lang.acl.UnreadableException;

/**
 * Handling the registration of participants on tables
 */
public class RegistrationServiceBehaviour extends CyclicBehaviour {

	private static final long serialVersionUID = 4299417511842916807L;
	private TableAgent tableAgent;

	private MessageTemplate mt;
	
	public RegistrationServiceBehaviour(TableAgent tableAgent) {
		this.tableAgent = tableAgent;
		mt = MessageTemplate.MatchConversationId(getConversationID());
	}

	public void action() {
		ACLMessage msg = tableAgent.receive(mt);
		if (msg != null) {
			// Message received. Process it
			ACLMessage reply = msg.createReply();
			AID participantAID = msg.getSender();
			//String content = msg.getContent();
			
			try {
				InterestSet content = (InterestSet) msg.getContentObject();
			
			if (!tableAgent.hasParticipant(participantAID)) {
				reply.setPerformative(ACLMessage.AGREE);
				tableAgent.addParticipant(participantAID, content);
				//System.out.println("Participant "+participantAID.getLocalName()+" registered on table "+tableAgent.getLocalName());
			}
			else {
				//System.out.println("Participant "+participantAID.getLocalName()+" already registered on table "+tableAgent.getLocalName());					
				reply.setPerformative(ACLMessage.REFUSE);
			}
			tableAgent.send(reply);
			} catch (UnreadableException e) {
				System.out.println("Deserialization Problem. \n" + e.getMessage());
			}
		} else {
			block();
		}
	}

	protected String getConversationID() {
		return Constants.REGISTRATION_REQUEST;
	}
	
}
